package br.com.CF.activitys;

import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;
import br.com.CF.R;
import br.com.CF.dao.ContaDao;
import br.com.CF.entidades.Conta;

public class TabFragmentA extends Fragment {

	private ListView listView;
	private List<Conta> contas;
	private ContaDao contaDao;
	private Conta conta;
	private View view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		if (container == null) {
			return null;
		}

		preencherListView(inflater, container);
		return(view);
	}

	public void preencherListView(LayoutInflater inflater, ViewGroup container) {
		contaDao = new ContaDao(getActivity());
		contas = contaDao.getAll();
		Log.i("ControleFinanceiro", "Tamanho da lista para mostrar: "+contas.size());

		view = (ScrollView)inflater.inflate(R.layout.tab_layout_a, container, false);

		listView = (ListView)view.findViewById(R.id.listViewConta);
		listView.setAdapter(new ArrayAdapter<Conta>(getActivity(), android.R.layout.simple_list_item_1, contas));
	}

	public void carregarWidgets() {
		Button saveButton = (Button)view.findViewById(R.id.btn_adicionar_conta);
		final EditText nmConta = (EditText)view.findViewById(R.id.nm_conta);
		final EditText descConta = (EditText)view.findViewById(R.id.desc_conta);
		final EditText saldo = (EditText)view.findViewById(R.id.saldo_conta);

		saveButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				try{
					createConta(nmConta.getEditableText().toString(), descConta.getEditableText().toString(), Double.parseDouble(saldo.getEditableText().toString()));
					nmConta.setText("");
					descConta.setText("");
					saldo.setText("");
					Toast.makeText(getActivity(), "Conta "+conta.getNm_conta()+" adicionada com sucesso!", Toast.LENGTH_SHORT).show();;

				}catch(Exception e){
					Toast.makeText(getActivity(), "Erro ao adicionar Conta!", Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	public void createConta(String nm_conta, String desc_conta, Double saldo) {
		contaDao = new ContaDao(getActivity());

		conta = new Conta();
		conta.setNm_conta(nm_conta);
		conta.setDesc_conta(desc_conta);
		conta.setSaldo(saldo);
		contaDao.createConta(conta);
	}

}